package br.com.bbcalibracao.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.bbcalibracao.bean.Calibracao;
import br.com.bbcalibracao.dao.CalibracaoDAO;
import br.com.bbcalibracao.form.CalibracaoForm;
import br.com.bbcalibracao.util.Constantes;
import br.com.bbcalibracao.util.Formatador;
import br.com.bbcalibracao.util.Validador;

public class ListagemCalibracaoAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
	@Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        try{
	        HttpSession sessao = request.getSession();
	        if (Validador.validaSessao(sessao)){
	        	CalibracaoForm loginForm = (CalibracaoForm) request.getAttribute("form");
	        	if (loginForm==null){
	        		String documento = (String) sessao.getAttribute(Validador.SESSAO);
	        		loginForm = obtemFormDocumento(documento);
	        	}
	        	List<Calibracao> cal = obtemCalibracoesCnpj(loginForm.getCnpj());
	        	loginForm.setLista(cal);
	            request.setAttribute("form", loginForm);
	            return mapping.findForward(Constantes.SUCCESS);
	        } else
	        	return mapping.findForward(Constantes.NAO_LOGADO);
        }catch (Exception e) {
        	return mapping.findForward(Constantes.ERROR);
		}
    }
	
	public List<Calibracao> obtemCalibracoesCnpj(String documento){
		documento = documento.replaceAll("\\.", "").replaceAll("\\-", "").replaceAll("\\/", "");
		CalibracaoDAO cDao = new CalibracaoDAO();
		List<Calibracao> lista = cDao.obtemCalibracao(documento);
		return lista;
    }
	
	public CalibracaoForm obtemFormDocumento(String doc){
		CalibracaoForm form = new CalibracaoForm();
		
		doc = doc.replaceAll("\\.", "").replaceAll("\\-", "").replaceAll("\\/", "");
		if (doc.length() == 11){
			doc = Formatador.formatarCpf(doc);
			form.setDocumento("cpf");
		} else {
			doc = Formatador.formatarCnpj(doc);
			form.setDocumento("cnpj");
		}
		form.setCnpj(doc);
		
		return form;
    }
}
